package com.example.javabasic.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * url工具类
 *
 * @author: cph
 * @date: 2021/12/1 14:27
 */
@Slf4j
public class ResolveUrlUtil {

    /**
     * 拼接请求参数到url中
     *
     * @param baseUrl
     * @param paramMap
     * @return
     */
    public static String joinUrl(String baseUrl, Map paramMap) {
        String url = baseUrl + "?";
        Iterator iterator = paramMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if (url.endsWith("?")) {
                url += key + "=" + value;
            } else {
                url += "&" + key + "=" + value;
            }
        }
        return url;
    }

    /**
     * 从url中解析参数
     *
     * @param url
     * @return
     */
    public static Map<String, String> getParams(String url) {
        Map<String, String> map = new HashMap<>();
        try {
            String str = url.substring(url.indexOf("?") + 1);
            for (String pair : str.split("&")) {
                String[] array = pair.split("=");
                // 如果为空则设置为”“；如果存在'#'则取‘#’之前的字符串
                //map.put(array[0], (array.length > 1 ? array[1] : "").split("#")[0]);
                map.put(array[0], array.length > 1 ? array[1] : "");
            }
        } catch (Exception e) {
            log.error("url解析异常: " + url, e);
        }
        return map;
    }

}
